const express = require("express");
const cors = require("cors");
const joi = require("joi");

const userRouter = require("./router/user");
const userInfoRouter = require("./router/userinfo");
const artCateRouter = require("./router/artcate");
const articleRouter = require("./router/article");
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());

app.use((req, res, next) => {
  res.cc = (err, status = 1) => {
    // err可能是一个错误对象或是字符串
    res.send({
      status,
      msg: err instanceof Error ? err.message : err,
    });
  };
  next();
});

// 解析token中间件
const expressJwt = require("express-jwt");
const config = require("./config/config");
app.use(
  expressJwt({ secret: config.jwtSecretKey }).unless({ path: [/^\/api/] })
);

app.use("/api", userRouter);
app.use("/my", userInfoRouter);
app.use("/my/article", artCateRouter);
app.use("/my/article", articleRouter);
// 错误级别的中间件
app.use((err, req, res, next) => {
  // 验证失败登录错误
  if (err instanceof joi.ValidationError) return res.cc(err);
  // 身份认证失败错误
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败");
  // 未知错误
  res.cc(err);
});

app.listen(8000, () => {
  console.log("800端口服务器已启动...");
});
